{% extends 'base.html' %}
{% load static %}

{% block title %}用户管理 - Allen监控系统{% endblock %}

{% block extra_css %}
<link href="{% static 'css/dataTables.bootstrap5.min.css' %}" rel="stylesheet">
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>用户管理</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal">
            <i class="fas fa-user-plus"></i> 新增用户
        </button>
    </div>

    <!-- 用户列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="usersTable">
                    <thead>
                        <tr>
                            <th>用户名</th>
                            <th>姓名</th>
                            <th>邮箱</th>
                            <th>用户组</th>
                            <th>状态</th>
                            <th>最后登录</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for user in users %}
                        <tr>
                            <td>{{ user.username }}</td>
                            <td>{{ user.first_name }} {{ user.last_name }}</td>
                            <td>{{ user.email }}</td>
                            <td>
                                {% for group in user.groups.all %}
                                <span class="badge bg-info">{{ group.name }}</span>
                                {% endfor %}
                            </td>
                            <td>
                                <span class="badge {% if user.is_active %}bg-success{% else %}bg-danger{% endif %}">
                                    {{ user.is_active|yesno:"启用,禁用" }}
                                </span>
                            </td>
                            <td>{{ user.last_login|default_if_none:"从未登录"|date:"Y-m-d H:i" }}</td>
                            <td>
                                <button class="btn btn-sm btn-primary edit-user" data-user-id="{{ user.id }}"
                                        data-bs-toggle="modal" data-bs-target="#userModal">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm {% if user.is_active %}btn-danger{% else %}btn-success{% endif %} toggle-status"
                                        data-user-id="{{ user.id }}" data-current-status="{{ user.is_active|yesno:'true,false' }}">
                                    <i class="fas {% if user.is_active %}fa-user-times{% else %}fa-user-check{% endif %}"></i>
                                </button>
                                <button class="btn btn-sm btn-warning reset-password" data-user-id="{{ user.id }}">
                                    <i class="fas fa-key"></i>
                                </button>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 用户表单模态框 -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="userModalLabel">新增用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    {% csrf_token %}
                    <input type="hidden" id="userId" name="user_id">
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="mb-3 password-field">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-control" id="password" name="password">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">姓名</label>
                        <div class="row">
                            <div class="col">
                                <input type="text" class="form-control" id="firstName" name="first_name" placeholder="名">
                            </div>
                            <div class="col">
                                <input type="text" class="form-control" id="lastName" name="last_name" placeholder="姓">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户组</label>
                        <select class="form-select" id="groups" name="groups" multiple>
                            {% for group in groups %}
                            <option value="{{ group.id }}">{{ group.name }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveUser">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'js/jquery.dataTables.min.js' %}"></script>
<script src="{% static 'js/dataTables.bootstrap5.min.js' %}"></script>
<script>
$(document).ready(function() {
    // 初始化DataTable
    $('#usersTable').DataTable({
        "language": {
            "url": "{% static 'js/datatables-zh.json' %}"
        }
    });

    // 重置表单
    function resetForm() {
        $('#userForm')[0].reset();
        $('#userId').val('');
        $('.password-field').show();
        $('#userModalLabel').text('新增用户');
    }

    // 打开新增用户模态框
    $('.btn-primary[data-bs-toggle="modal"]').click(function() {
        resetForm();
    });

    // 编辑用户
    $('.edit-user').click(function() {
        const userId = $(this).data('user-id');
        $('#userModalLabel').text('编辑用户');
        $('.password-field').hide();
        
        $.get(`{% url 'get_user' %}?user_id=${userId}`, function(data) {
            $('#userId').val(data.id);
            $('#username').val(data.username);
            $('#firstName').val(data.first_name);
            $('#lastName').val(data.last_name);
            $('#email').val(data.email);
            $('#groups').val(data.groups);
        });
    });

    // 保存用户
    $('#saveUser').click(function() {
        const formData = new FormData($('#userForm')[0]);
        const userId = $('#userId').val();
        const url = userId ? '{% url "update_user" %}' : '{% url "create_user" %}';

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.status === 'success') {
                    location.reload();
                } else {
                    alert(response.message);
                }
            },
            error: function(xhr) {
                alert('操作失败：' + xhr.responseText);
            }
        });
    });

    // 切换用户状态
    $('.toggle-status').click(function() {
        const userId = $(this).data('user-id');
        const currentStatus = $(this).data('current-status');
        const newStatus = !currentStatus;
        
        if (confirm(`确定要${newStatus ? '启用' : '禁用'}该用户吗？`)) {
            $.post('{% url "toggle_user_status" %}', {
                user_id: userId,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            }, function(response) {
                if (response.status === 'success') {
                    location.reload();
                } else {
                    alert(response.message);
                }
            });
        }
    });

    // 重置密码
    $('.reset-password').click(function() {
        const userId = $(this).data('user-id');
        if (confirm('确定要重置该用户的密码吗？')) {
            $.post('{% url "reset_password" %}', {
                user_id: userId,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            }, function(response) {
                if (response.status === 'success') {
                    alert(`新密码：${response.password}`);
                } else {
                    alert(response.message);
                }
            });
        }
    });
});
</script>
{% endblock %} 